package com.ask.forMe.config;

import com.ask.forMe.model.entity.UserContext;
import com.ask.forMe.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;


@Slf4j
public class UserContextInterceptor implements HandlerInterceptor {

    private UserService userService;

    public UserContextInterceptor(UserService userService) {
        this.userService = userService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 校验成功后
        UserContext userContext = userService.loadUserContext("token");
        UserContextHolder.setUserContext(userContext);

        log.info("存储用户上下文至ThreadLocal");
        return true;
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContextHolder.removeUserContext();
    }
}
